package com.mdd.utils;

import org.apache.commons.lang.StringUtils;

public class HexUtil {
    private static final char[] UPPER_HEX = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    public final static String HEX_DIGITS = "0123456789ABCDEF";


    /**
     * byte转16进制
     *
     * @param bytes 字节
     * @return String
     */
    public static String byteToHexStr(byte[] bytes) {
        if (null == bytes || bytes.length == 0) {
            return null;
        }
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            //高4位字节
            hexChars[j * 2] = UPPER_HEX[v >>> 4];
            //低四位字节
            hexChars[j * 2 + 1] = UPPER_HEX[v & 0x0F];
        }
        return new String(hexChars);
    }


    /**
     * 16进制字符串转byte
     * @param hexStr 转换字符串
     * @return byte[]
     */
    public static byte[] hexStrToByte(String hexStr) {
        if (StringUtils.isEmpty(hexStr)) {
            return null;
        }
        //一个字节8位,hexStr一个字符4位,所以byte长度为hexStr.length/2
        //判断是否是偶数,非偶数首位补0
        if ((hexStr.length() & 1) != 0) {
            hexStr = "0" + hexStr;
        }
        //一个字节8位,hexStr一个字符4位,所以byte长度为hexStr.length/2
        int len = hexStr.length() / 2;
        byte[] bytes = new byte[len];
        //字节高4位
        byte high;
        //字节低4位
        byte low = 0;
        int pos = 0;
        for (int i = 0; i < len; i++) {
            pos = 2 * i;
            high = (byte)(HEX_DIGITS.indexOf(hexStr.charAt(pos)) << 4);
            low = (byte)(HEX_DIGITS.indexOf(hexStr.charAt(pos + 1)));
            bytes[i] = (byte)(high | low);
        }
        return bytes;
    }
}
